package com.flyduck.vueshop.common.upload.manager;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.ArrayUtil;
import com.flyduck.vueshop.common.core.exception.BusinessException;
import com.flyduck.vueshop.common.core.utils.DateUtils;
import com.flyduck.vueshop.common.core.utils.StringUtils;
import com.flyduck.vueshop.common.upload.properties.CosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.util.ArrayUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * AppUploadManager
 * </p>
 *
 * @author flyduck
 * @since 2024/5/8
 */
@Component
public class AppUploadManager {

    @Autowired
    private CosProperties cosProperties;

    /**
     * 上传图片到腾讯云
     * @param pictures 需要上传的图片列表
     * @param scale 缩小比例
     * @param quality 压缩比例
     * @return
     * @throws IOException
     */
    public List<String> upload(MultipartFile[] pictures, float scale, double quality) throws IOException {
        List<String> resultList = new ArrayList<>();

        //1、检查图片是否符合要求
        if (ArrayUtil.isEmpty(pictures)) {
            return new ArrayList<>();
        }

        String yyyy_mm_dd = DateUtils.getYYYY_MM_DD();
        for (MultipartFile picture : pictures) {
            String type = FileTypeUtil.getType(picture.getInputStream());
            if (StringUtils.isBlank(type)) {
                throw new BusinessException("图片类型不合法");
            }
            if (!Arrays.asList("png","jpg","jpeg").contains(type.toLowerCase())) {
                throw new BusinessException("不支持的图片类型");
            }

            //2、压缩图片（图片太大：1：占用云空间、2：前端加载比较慢）
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Img.from(picture.getInputStream())
                    .scale(scale)
                    .setQuality(quality)
                    .write(outputStream);

            //3、上传到腾讯云
            String key = UUID.randomUUID().toString();
            String path = "images/" + yyyy_mm_dd + "/" + key + "." + type;
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), path,new ByteArrayInputStream(outputStream.toByteArray()),null);
            getClient().putObject(putObjectRequest);

            //4、组合图片访问路径
            String picturePath = "http://" + cosProperties.getBucketName() + ".cos." + cosProperties.getRegion() + ".myqcloud.com/" + path;
            resultList.add(picturePath);
        }
        return resultList;
    }

    private COSClient getClient(){
        // 设置用户身份信息。
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        String secretId = cosProperties.getSecretId();//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        String secretKey = cosProperties.getSecretKey();//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // ClientConfig 中包含了后续请求 COS 的客户端设置：
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion(new Region(cosProperties.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 设置 socket 读取超时，默认 30s
        clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时，默认 30s
        clientConfig.setConnectionTimeout(30*1000);

        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);

    }
}
